import {
  addNewPageItemByForm,
  addNewUserByForm,
  deletePageItemById,
  deleteUserById,
  editPageItemByForm,
  editUserInfo,
  postPageListsData,
  postUserListsData
} from '@/service/main/system/system'
import type { IUserStore } from '@/types/main_user'
import { defineStore } from 'pinia'

export const useSystemStore = defineStore('system', {
  state: (): IUserStore => ({
    userLists: [],
    userTotalCount: 0,
    pageLists: [],
    pageTotalCount: 0
  }),
  actions: {
    async postUsersListsAction(queryInfo: any) {
      const result = await postUserListsData(queryInfo)
      const { list, totalCount } = result.data
      this.userLists = list
      this.userTotalCount = totalCount
    },
    async deleteUserByIdAction(id: number) {
      const deleteResult = await deleteUserById(id)
      console.log(deleteResult)
      this.postUsersListsAction({ size: 10, offset: 0 })
    },
    async addNewUserAction(userInfo: any) {
      const addResult = await addNewUserByForm(userInfo)
      console.log(addResult)
      // 重新请求
      this.postUsersListsAction({ size: 10, offset: 0 })
    },
    async editUserInfoAction(id: number, userInfo: any) {
      const editResult = await editUserInfo(id, userInfo)
      console.log(editResult)
      // 重新请求
      this.postUsersListsAction({ size: 10, offset: 0 })
    },
    // page
    async postPageListsAction(pageName: string, queryInfo: any) {
      const pageResult = await postPageListsData(pageName, queryInfo)
      console.log('pageResult', pageResult)
      const { list, totalCount } = pageResult.data
      console.log('page:', list, totalCount)
      this.pageLists = list
      this.pageTotalCount = totalCount
    },
    async deletePageItemByIdAction(pageName: string, id: number) {
      const deleteResult = await deletePageItemById(pageName, id)
      console.log(deleteResult)
      this.postPageListsAction(pageName, { size: 10, offset: 0 })
    },
    async addNewPageItemAction(pageName: string, userInfo: any) {
      await addNewPageItemByForm(pageName, userInfo)

      // 重新请求
      this.postPageListsAction(pageName, { size: 10, offset: 0 })
    },
    async editPageItemByFormAction(
      pageName: string,
      id: number,
      userInfo: any
    ) {
      await editPageItemByForm(pageName, id, userInfo)
      // 重新请求
      this.postPageListsAction(pageName, { size: 10, offset: 0 })
    }
  }
})
